/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.protostuff;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 卢清波
 * @date 2021/2/1 16:06
 */
public class ProtoStuffUtil
{

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();


    public static <T>Schema<T> getSchema(Class<T> clazz)
    {
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (null == schema)
        {
            schema = RuntimeSchema.getSchema(clazz);
        }
        cachedSchema.put(clazz,schema);
        return schema;
    }


    public static <T> byte[] serializeData(T obj)
    {
        Class<T> aClass = (Class<T>) obj.getClass();
        Schema<T> schema = getSchema(aClass);
        LinkedBuffer linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] bytes = ProtostuffIOUtil.toByteArray(obj, schema, linkedBuffer);
        return bytes;
    }

    public static <T> T  deSerializeData(byte[] bytes,Class<T> clazz) throws IllegalAccessException, InstantiationException
    {

        Schema<T> schema = getSchema(clazz);
        T t = clazz.newInstance();
        ProtostuffIOUtil.mergeFrom(bytes,t,schema);
        return t ;
    }


    public static void main(String[] args) throws InstantiationException, IllegalAccessException
    {
        Test test = new Test("kason",19);
        byte[] bytes = ProtoStuffUtil.serializeData(test);

        Test test1 = ProtoStuffUtil.deSerializeData(bytes, Test.class);
        System.out.println(test1.toString());

    }
}
